package com.work.saturn.mine;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.coorchice.library.SuperTextView;
import com.immo.libcommon.base.BaseFragment;
import com.immo.libcommon.constant.BaseUrl;
import com.immo.libcommon.constant.RouterUtil;
import com.immo.libcommon.constant.SharePreferenceKey;
import com.immo.libcommon.http.NetworkRequest;
import com.immo.libcommon.utils.FullyLinearLayoutManager;
import com.immo.libcommon.utils.SharePreferenceUtils;
import com.immo.libcommon.view.MyDialog;
import com.work.saturn.R;
import com.work.saturn.bean.TokenListBean;
import com.work.saturn.bean.UserMsgBean;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


/**
 * @author Administrator
 * @content 我的
 * @date 2018/7/10
 */
@Route(path = RouterUtil.MINE_FRAGMENT)
public class MineFragment extends BaseFragment {
    Unbinder unbinder;
    @BindView(R.id.user_id)
    TextView mUserId;
    @BindView(R.id.user_list_02)
    RecyclerView mList02;
    @BindView(R.id.user_list_01)
    RecyclerView mList01;
    @BindView(R.id.mine_srl)
    SwipeRefreshLayout mRefresh;
    @BindView(R.id.user_gas_name)
    EditText mUserGasName;
    private boolean isPrepared = false;
    private List<String> listdata01 = new ArrayList<>();
    private List<String> listdata02 = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        isPrepared = true;
        lazyLoad();
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
        initUI();
    }

    /**
     * 查询用户等待创建的token
     */
    private void interestList01() {
        HashMap<String, String> params = new HashMap<>();
        params.put("username", Objects.requireNonNull(SharePreferenceUtils.get(Objects.requireNonNull(getActivity()), SharePreferenceKey.USERNAME, "")).toString());
        new NetworkRequest((object, data) -> {
            if (object instanceof TokenListBean) {
                TokenListBean tokenListBean = (TokenListBean) object;
                if (tokenListBean.getData().size() != 0) {
                    for (int i = 0; i < tokenListBean.getData().size(); i++) {
                        listdata01.add("Token      " + tokenListBean.getData().get(i).getName());
                    }
                }

            }
            interestList02();
        }).requestPostKey(BaseUrl.QUERY_WAITING, getActivity(), params, TokenListBean.class, true, false);
    }

    /**
     * 查询用户创建成功的Token
     */
    private void interestList02() {
        HashMap<String, String> params = new HashMap<>();
        params.put("username", Objects.requireNonNull(SharePreferenceUtils.get(Objects.requireNonNull(getActivity()), SharePreferenceKey.USERNAME, "")).toString());
        new NetworkRequest((object, data) -> {
            if (object instanceof TokenListBean) {
                TokenListBean tokenListBean = (TokenListBean) object;
                if (tokenListBean.getData().size() != 0) {
                    for (int i = 0; i < tokenListBean.getData().size(); i++) {
                        listdata02.add("Token      " + tokenListBean.getData().get(i).getName());
                    }
                    initList01Data();
                    initList2Data();
                }
            }
        }).requestPostKey(BaseUrl.QUERY_APPROVED, getActivity(), params, TokenListBean.class, true, false);
    }

    private void initUI() {
        mUserId.setText(Objects.requireNonNull(SharePreferenceUtils.get(Objects.requireNonNull(getActivity()), SharePreferenceKey.USERNAME, "")).toString());
//        interestList01();
    }

    /**
     * 初始化列表1数据
     */
    private void initList01Data() {

        FullyLinearLayoutManager linearLayoutManagerTheme = new FullyLinearLayoutManager(getActivity()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        linearLayoutManagerTheme.setOrientation(LinearLayoutManager.VERTICAL);
        mList01.setLayoutManager(linearLayoutManagerTheme);
        ToKenList1Adapter toKenList1Adapter = new ToKenList1Adapter();
        //设置适配器
        toKenList1Adapter.bindToRecyclerView(mList01);
    }

    /**
     * 初始化列表2数据
     */
    private void initList2Data() {
        FullyLinearLayoutManager linearLayoutManagerTheme = new FullyLinearLayoutManager(getActivity()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        linearLayoutManagerTheme.setOrientation(LinearLayoutManager.VERTICAL);
        mList02.setLayoutManager(linearLayoutManagerTheme);
        ToKenList2Adapter toKenList2Adapter = new ToKenList2Adapter();
        //设置适配器
        toKenList2Adapter.bindToRecyclerView(mList02);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * 退出登录
     */
    private void toOutLogin() {
        SharePreferenceUtils.put(Objects.requireNonNull(getActivity()), SharePreferenceKey.USERNAME, "");
        SharePreferenceUtils.put(getActivity(), SharePreferenceKey.TOKEN, "");
        ARouter.getInstance().build(RouterUtil.LOGIN_PAGE).withFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK).navigation();
        getActivity().finish();
    }

    /**
     * 获取用户信息
     */
    private void getUserMsg() {

        new NetworkRequest((object, data) -> {
            if (object instanceof UserMsgBean) {
                UserMsgBean userMsgBean = (UserMsgBean) object;
                if (userMsgBean.isSuccess()) {
                    if (userMsgBean.getPayload().isCanCreateNewToken()) {
//                        ARouter.getInstance().build(RouterUtil.CREATE_TOKEN).navigation();
                    } else {
                        toast("您的账号没有创建Token权限，请联系管理员授予");
                    }
                }

            }
        }).requestGet(BaseUrl.GETUSERMSG + Objects.requireNonNull(SharePreferenceUtils.get(Objects.requireNonNull(getActivity()), SharePreferenceKey.USERNAME, "")).toString(),
                getActivity(), UserMsgBean.class, true, false);
    }

    @OnClick({R.id.user_token, R.id.user_loginout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.user_token:
//                getUserMsg();
                if (mUserGasName.getText().toString().length()==0){
                    toast("Token名称不能为空");
                    return;
                }
                ARouter.getInstance().build(RouterUtil.CHANGE_TOKEN_PAGE).withString("tokenName",mUserGasName.getText().toString()).navigation();
                break;
            case R.id.user_loginout:
                MyDialog.dialogShow(getActivity(), "你确定要退出账号吗？", "取消", "确定", this::toOutLogin);
                break;
        }
    }


    /**
     * 用户列表2
     */
    private class ToKenList2Adapter extends BaseQuickAdapter<String, BaseViewHolder> {
        ToKenList2Adapter() {
            super(R.layout.item_fragment_mine_02, listdata01);
        }

        @Override
        protected void convert(BaseViewHolder helper, String item) {
            helper.setText(R.id.item_list02_name, item);
            SuperTextView gas = helper.getView(R.id.item_list02_change_gas);
            gas.setOnClickListener(view -> ARouter.getInstance().build(RouterUtil.CHANGE_TOKEN_PAGE).withInt("type", 0).navigation());
            SuperTextView ram = helper.getView(R.id.item_list02_change_Ram);
            ram.setOnClickListener(view -> ARouter.getInstance().build(RouterUtil.CHANGE_TOKEN_PAGE).withInt("type", 1).navigation());
        }

    }

    /**
     * 用户列表1
     */
    private class ToKenList1Adapter extends BaseQuickAdapter<String, BaseViewHolder> {
        ToKenList1Adapter() {
            super(R.layout.item_fragment_mine_01, listdata01);
        }

        @Override
        protected void convert(BaseViewHolder helper, String item) {
            helper.setText(R.id.item_list_name, item);
        }

    }
}
